#include "Qt3DPicker.h"

#include "ExplodeHandler.h"
#include "CmdManager.h"
#include "Registry.h"
#include "ActorTable.h"
#include "Scene.h"
#include "SendPointHandlerBase.h"
#include "SelectHandler3D.h"
#include "OSGNodeMask.h"
#include "Operation/OpReplace.h"

ExplodeHandler::ExplodeHandler()
{
}

ExplodeHandler::~ExplodeHandler()
{
}

void ExplodeHandler::input(const QVariant& data, const QString& rawInput, CommandSource cs)
{
	auto scene = getScene();
	auto ucs = scene->getCurrentUCS();
	auto sph = getSendPointHandler();
	auto selector = qobject_cast<SelectHandler3D*>(getSelectHandler());
	if (data.type() == QVariant::Bool)
	{
		bool esc = !data.toBool();
		if (esc)
		{
			selector->clearSelection();
			clearInput();
			emit finished();
			return;
		}
	}

	if (status() == 0)
	{
		if (selector)
		{
			selector->clearSelection();
			selector->beginSelect(D2CurveMask | D3CurveMask);
			prompt(1, tr("选择对象: "));
		}
		else
		{
			emit finished();
		}
		return;
	}

	if (status() == 1)
	{
		if (selector && selector->done())
		{
			auto selections = selector->selectionSet();
			if (selections.size() > 0)
			{
				std::vector<std::shared_ptr<Ent>> origins;
				std::vector<std::shared_ptr<Ent>> explodes;
				for (auto selection : selections)
				{
					std::shared_ptr<Ent> ent = std::dynamic_pointer_cast<Ent>(selection);
					if (ent)
					{
						std::vector<std::shared_ptr<Ent>> result;
						bool exploded = ent->explode(result);
						if (exploded)
						{
							origins.push_back(ent);
							explodes.insert(explodes.end(), result.begin(), result.end());
						}
					}
				}
				selector->clearSelection();
				if (origins.size() > 0)
				{
					auto undoStack = scene->undoStack();
					undoStack->push(new OpReplace(origins, explodes));
				}
				emit finished();
			}
		}
		return;
	}

}